<template>
    <div class="medical-navigator h-full overflow-y-auto bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700">
      <div class="p-4 border-b border-gray-200 dark:border-gray-700">
        <h2 class="text-lg font-semibold flex items-center">
          <i class="fa fa-list-ul mr-2 text-primary"></i>
          文档导航
        </h2>
      </div>
      
      <div class="p-3">
        <!-- 搜索框 -->
        <div class="mb-3">
          <div class="relative">
            <input
              type="text"
              v-model.lazy="searchQuery"
              placeholder="搜索章节..."
              class="w-full px-3 py-2 pl-9 pr-3 text-sm bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
            />
            <i class="fa fa-search absolute left-3 top-2.5 text-gray-400"></i>
          </div>
        </div>
        
        <!-- 导航树 -->
        <ul class="space-y-1 overflow-y-auto max-h-[calc(100%-200px)]">
          <TreeNode
            v-for="(node, index) in filteredNodes"
            :key="node.id || index"
            :node="node"
            :depth="0"
            :active-id="activeNodeId"
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
          />
        </ul>
        
        <!-- 模板快捷方式 -->
        <div class="mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
          <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">文档模板</h3>
          <div class="space-y-2">
            <button
              v-for="template in availableTemplates"
              :key="template.id"
              class="w-full px-3 py-2 text-left rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-sm flex items-center"
              @click="applyTemplate(template.id)"
            >
              <i class="fa fa-file-text-o mr-2 text-gray-500 dark:text-gray-400"></i>
              {{ template.name }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
  import { useEditorStore } from '../stores/editorStore';
  import { useTemplateStore } from '../stores/templateStore';
  import type { MedicalElement, MedicalDocument } from '../types/medicalTypes';
  
  interface Template {
    id: string;
    name: string;
    content: MedicalDocument;
  }

  interface TreeNode {
    id: string;
    type: string;
    title: string;
    level: number;
    element: MedicalElement;
    children: TreeNode[];
    expanded: boolean;
    index: number;
    parent?: TreeNode;
  }
  
  const emit = defineEmits(['node-selected']);
  
  const editorStore = useEditorStore();
  const templateStore = useTemplateStore();
  const searchQuery = ref('');
  const activeNodeId = ref('');
  
  const availableTemplates = computed<Template[]>(() => 
  templateStore.getAllTemplates()
);
  
  const buildDocumentTree = (document: MedicalDocument): TreeNode[] => {
    const tree: TreeNode[] = [];
    let currentParent: TreeNode | null = null;
    let currentLevel = 0;
    
    document.forEach((element, index) => {
      if (shouldIncludeInTree(element)) {
        const node = createTreeNode(element, index);
        buildTreeStructure(tree, node, currentParent, currentLevel);
        currentParent = node;
        currentLevel = node.level;
      }
    });
    
    return tree;
  };
  
  const shouldIncludeInTree = (element: MedicalElement): boolean => {
    return element.type === 'heading' || element.type !== 'paragraph';
  };
  
  const createTreeNode = (element: MedicalElement, index: number): TreeNode => {
    const firstChild = element.children[0];
    const title = (firstChild && 'text' in firstChild) ? firstChild.text : '无标题';
    
    return {
      id: `node-${index}`,
      type: element.type,
      title,
      level: element.type === 'heading' ? 1 : 2,
      element,
      children: [],
      expanded: true,
      index
    };
  };
  
  const buildTreeStructure = (
    tree: TreeNode[],
    node: TreeNode,
    currentParent: TreeNode | null,
    currentLevel: number
  ) => {
    if (node.level > currentLevel) {
      handleChildNode(tree, node, currentParent);
    } else if (node.level === currentLevel) {
      handleSiblingNode(tree, node, currentParent);
    } else {
      handleParentNode(tree, node, currentParent);
    }
  };
  
  const handleChildNode = (tree: TreeNode[], node: TreeNode, currentParent: TreeNode | null) => {
    if (currentParent) {
      currentParent.children.push(node);
      node.parent = currentParent;
    } else {
      tree.push(node);
    }
  };
  
  const handleSiblingNode = (tree: TreeNode[], node: TreeNode, currentParent: TreeNode | null) => {
    if (currentParent?.parent) {
      currentParent.parent.children.push(node);
      node.parent = currentParent.parent;
    } else {
      tree.push(node);
    }
  };
  
  const handleParentNode = (tree: TreeNode[], node: TreeNode, currentParent: TreeNode | null) => {
    let parent = currentParent;
    while (parent && parent.level >= node.level) {
      parent = parent.parent || null;
    }
    
    if (parent) {
      parent.children.push(node);
      node.parent = parent;
    } else {
      tree.push(node);
    }
  };

  const documentTree = computed(() => buildDocumentTree(editorStore.editorValue));
  
  const filteredNodes = computed(() => {
    if (!searchQuery.value.trim()) return documentTree.value;
    
    const query = searchQuery.value.toLowerCase();
    return filterNodes(documentTree.value, query);
  });
  
  const filterNodes = (nodes: TreeNode[], query: string): TreeNode[] => {
    return nodes
      .map(node => {
        const filteredChildren = filterNodes(node.children, query);
        const matches = node.title.toLowerCase().includes(query);
        
        return {
          ...node,
          children: filteredChildren,
          expanded: matches || filteredChildren.length > 0
        };
      })
      .filter(node => node.title.toLowerCase().includes(query) || node.children.length > 0);
  };
  
  const handleNodeClick = (node: TreeNode) => {
    activeNodeId.value = node.id;
    emit('node-selected', node.index);
  };
  
  const handleNodeExpand = (node: TreeNode) => {
    node.expanded = !node.expanded;
  };
  
  const applyTemplate = async (templateId: string) => {
    try {
      await templateStore.loadTemplate(templateId);
      if (templateStore.currentTemplate?.content) {
        editorStore.setEditorValue([...templateStore.currentTemplate.content]);
      }
    } catch (error) {
      console.error('加载模板失败:', error);
    }
  };
  
  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      e.preventDefault();
      // 实现键盘导航逻辑
    }
  };
  
  onMounted(() => {
    window.addEventListener('keydown', handleKeyDown);
  });
  
  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown);
  });
  
  watch(
    () => editorStore.editorValue,
    () => activeNodeId.value = '',
    { deep: true }
  );
  </script>
  
  <style scoped>
  .medical-navigator {
    scrollbar-width: thin;
    scrollbar-color: theme('colors.gray.300') theme('colors.gray.100');
  }

  .medical-navigator::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  .medical-navigator::-webkit-scrollbar-track {
    background: theme('colors.gray.100');
  }

  .medical-navigator::-webkit-scrollbar-thumb {
    background-color: theme('colors.gray.300');
    border-radius: 20px;
  }

  .dark .medical-navigator {
    scrollbar-color: theme('colors.gray.600') theme('colors.gray.800');
  }

  .dark .medical-navigator::-webkit-scrollbar-track {
    background: theme('colors.gray.800');
  }

  .dark .medical-navigator::-webkit-scrollbar-thumb {
    background-color: theme('colors.gray.600');
  }
  </style>